﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Himp.Platform.Api
{
    public class OpenApiService: ApiAppService, IOpenApiService
    {
        private readonly IServiceProvider _serviceProvider;
        private ILogger<OpenApiService> _logger;

        public OpenApiService(IServiceProvider serviceProvider
            , ILogger<OpenApiService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="infNo"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<OpenApiOutput> Post(string msgId, string infNo, string input)
        {
            _logger.LogInformation(msgId, infNo, input);
            //通过infNo判断接口类型
            OpenApiOutput openApiOutput = new OpenApiOutput();
            //接口类别：plugIns、同步http、异步kafka、定时任务job
            var service = _serviceProvider.GetServices<IOpenApiHandle>().FirstOrDefault(s =>
                s.InfNo == infNo && s.ApiEnvType == EnumApiEnvType.开发环境);

            if (service == null)
            {
                openApiOutput.InfCode = -1;
                openApiOutput.ErrMsg = "未找到有效的接口服务";
                return openApiOutput;
            }

            var result = await service.Post(input);
            openApiOutput.InfRefMsgId = msgId;
            openApiOutput.InfCode = result.Code;
            openApiOutput.ErrMsg = result.ErrorMsg;
            openApiOutput.Output = result.Data;

            return openApiOutput;
        }
    }
}
